//
//  XLUnlockSettingVC.m
//  industry
//
//  Created by xl on 2020/12/14.
//  Copyright © 2020 Haier. All rights reserved.
//

#import "XLUnlockSettingVC.h"
#import "XLUnlockSettingAdapter.h"
#import "UIDevice+XL.h"
#import "XLUserDefaults.h"
#import "XLPasswordVC.h"
#import "XLAlert.h"
#import "XLGestureLockVC.h"
#import <LocalAuthentication/LocalAuthentication.h>

@interface XLUnlockSettingVC ()<XLAdapterDelegate>

@property (nonatomic, strong) XLTableView *tableView;
@property (nonatomic, strong) XLUnlockSettingAdapter *adapter;

@end

@implementation XLUnlockSettingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"解锁设置";
    [self buildView];
    
}

- (void)buildView {
    [self.view addSubview:self.tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(self.view);
    }];
    
    NSMutableArray *arr = [NSMutableArray array];
    [arr addObjectsFromArray:@[XLUnlockSettingAdapterPasswordUnlock,
                               XLUnlockSettingAdapterGestureUnlock]];
    if ([[UIDevice currentDevice] isCurrentSupportTouchId]) {
        [arr addObject:XLUnlockSettingAdapterFingerprintUnlock];
    }
    if ([[UIDevice currentDevice] isCurrentSupportFaceId]) {
        [arr addObject:XLUnlockSettingAdapterBrushFaceUnlock];
    }
    [arr addObject:XLUnlockSettingAdapterNoneUnlock];
    [_adapter setAdapterArray:arr];
    
    //获取之前存储的选择登录方式
    switch ([XLUserDefaults getLastLoginWay]) {
        case XLLoginWayTypeNoneUnlock:
            _adapter.type = XLUnlockSettingAdapterNoneUnlock;
            break;
        case XLLoginWayTypePasswordUnlock:
            _adapter.type = XLUnlockSettingAdapterPasswordUnlock;
            break;
        case XLLoginWayTypeGestureUnlock:
            _adapter.type = XLUnlockSettingAdapterGestureUnlock;
            break;
        case XLLoginWayTypeFingerprintUnlock:
            _adapter.type = XLUnlockSettingAdapterFingerprintUnlock;
            break;
        case XLLoginWayTypeBrushFaceUnlock:
            _adapter.type = XLUnlockSettingAdapterBrushFaceUnlock;
            break;
        default:
            break;
    }
    [_tableView reloadData];
}

#pragma mark - XLAdapterDelegate
- (void)didSelectCellData:(id)cellData {
    if ([cellData isEqualToString:_adapter.type]) {
        if ([cellData isEqualToString:XLUnlockSettingAdapterPasswordUnlock]) {//修改数字密码
            [self gotoPasswordVC:XLPasswordVCFromTypeModify];
        } else if ([cellData isEqualToString:XLUnlockSettingAdapterGestureUnlock]) {//修改手势密码
            [self gotoGesturePasswordVC:XLGestureLockVCFromTypeModify];
        } else if ([cellData isEqualToString:XLUnlockSettingAdapterFingerprintUnlock] ||
                   [cellData isEqualToString:XLUnlockSettingAdapterBrushFaceUnlock] ||
                   [cellData isEqualToString:XLUnlockSettingAdapterNoneUnlock]) {
            return;
        }
    } else {
        if ([cellData isEqualToString:XLUnlockSettingAdapterPasswordUnlock]) {
            NSString *lastPS = [XLUserDefaults getLastNumPassword];
            if (ISEmptyString(lastPS)) {//前往设置数字密码
                [self gotoPasswordVC:XLPasswordVCFromTypeSetting];
            } else {//之前已经有数字密码
                _adapter.type = cellData;
                [_tableView reloadData];
                [XLUserDefaults saveLastLoginWay:XLLoginWayTypePasswordUnlock];
            }
        } else if ([cellData isEqualToString:XLUnlockSettingAdapterGestureUnlock]) {
            NSString *lastPS = [XLUserDefaults getLastGesturePassword];
            if (ISEmptyString(lastPS)) {
                [self gotoGesturePasswordVC:XLGestureLockVCFromTypeSetting];
            } else {
                _adapter.type = cellData;
                [_tableView reloadData];
                [XLUserDefaults saveLastLoginWay:XLLoginWayTypeGestureUnlock];
            }
        } else if ([cellData isEqualToString:XLUnlockSettingAdapterFingerprintUnlock]) {
            //开始指纹校验
            [self startFaceIdOrTouchIDCheck:XLUnlockSettingAdapterFingerprintUnlock];
        } else if ([cellData isEqualToString:XLUnlockSettingAdapterBrushFaceUnlock]) {
            //开始脸部识别校验
            [self startFaceIdOrTouchIDCheck:XLUnlockSettingAdapterBrushFaceUnlock];
        } else if ([cellData isEqualToString:XLUnlockSettingAdapterNoneUnlock]) {
            [XLUserDefaults saveLastLoginWay:XLLoginWayTypeNoneUnlock];
            //清空数字密码
            [XLUserDefaults saveLastNumPassword:nil];
            //清空手势密码
            [XLUserDefaults saveLastGesturePassword:nil];
            _adapter.type = cellData;
            [_tableView reloadData];
        }
    }
}

#pragma mark - Jump
//密码设置
- (void)gotoPasswordVC:(XLPasswordVCFromType)type {
    XLPasswordVC *vc = [[XLPasswordVC alloc] init];
    vc.type = type;
    vc.resultBlock = ^{
        self->_adapter.type = XLUnlockSettingAdapterPasswordUnlock;
        [self->_tableView reloadData];
        [XLUserDefaults saveLastLoginWay:XLLoginWayTypePasswordUnlock];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

//设置手势密码
- (void)gotoGesturePasswordVC:(XLGestureLockVCFromType)type {
    XLGestureLockVC *vc = [[XLGestureLockVC alloc] init];
    vc.type = type;
    vc.resultBlock = ^{
        self->_adapter.type = XLUnlockSettingAdapterGestureUnlock;
        [self->_tableView reloadData];
        [XLUserDefaults saveLastLoginWay:XLLoginWayTypeGestureUnlock];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Private
- (void)startFaceIdOrTouchIDCheck:(NSString *)type {
    LAContext *myContext = [[LAContext alloc] init];
    // 这个属性是设置指纹输入失败之后的弹出框的选项
    myContext.localizedFallbackTitle = @"忘记密码";
    NSError *authError = nil;
    NSString *myLocalizedReasonString = @"请按住Home键完成验证";
    if ([myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&authError])
        {
            [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:myLocalizedReasonString reply:^(BOOL success, NSError * _Nullable error) {
                if(success)
                {
                    NSLog(@"指纹认证成功");
                    [self saveSafeLoginWay:type];
                } else {
                    NSLog(@"指纹认证失败，%@",error.description);

                    NSLog(@"%ld", (long)error.code); // 错误码 error.code
                    switch (error.code)
                    {
                        case LAErrorAuthenticationFailed: // Authentication was not successful, because user failed to provide valid credentials
                        {
                            NSLog(@"授权失败"); // -1 连续三次指纹识别错误
                            BOOL can = [myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error];
                            if (can) {
                                [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"连续3次指纹或者脸部识别错误，请再次指纹或脸部识别" reply:^(BOOL success, NSError * _Nullable error) {
                                    if (!error) {
                                         NSLog(@"密码输入成功！");
                                        [self saveSafeLoginWay:type];
                                    } else {
                                        NSLog(@"密码输入错误！");
                                    }
                                }];
                            }else{
                                NSLog(@"调起账号密码页面失败!!!");
                                
                            }
                        }
                            break;
                        case LAErrorUserCancel: // Authentication was canceled by user (e.g. tapped Cancel button)
                        {
                            NSLog(@"用户取消验证Touch ID"); // -2 在TouchID对话框中点击了取消按钮
                        }
                            break;
                        case LAErrorUserFallback: // Authentication was canceled, because the user tapped the fallback button (Enter Password)
                        {
                            NSLog(@"用户选择输入密码，切换主线程处理"); // -3
                        }
                            break;
                        case LAErrorSystemCancel: // Authentication was canceled by system (e.g. another application went to foreground)
                        {
                            NSLog(@"取消授权，如其他应用切入，用户自主"); // -4 TouchID对话框被系统取消，例如按下Home或者电源键
                        }
                            break;
                        case LAErrorPasscodeNotSet: // Authentication could not start, because passcode is not set on the device.
                        {
                            NSLog(@"设备系统未设置密码"); // -5
                        }
                            break;
                        case LAErrorTouchIDNotAvailable: // Authentication could not start, because Touch ID is not available on the device
                        {
                            NSLog(@"设备未设置Touch ID"); // -6
                        }
                            break;
                        case LAErrorTouchIDNotEnrolled: // Authentication could not start, because Touch ID has no enrolled fingers
                        {
                            NSLog(@"用户未录入指纹"); // -7
                        }
                            break;
                        case LAErrorTouchIDLockout: //Authentication was not successful, because there were too many failed Touch ID attempts and Touch ID is now locked. Passcode is required to unlock Touch ID, e.g. evaluating LAPolicyDeviceOwnerAuthenticationWithBiometrics will ask for passcode as a prerequisite 用户连续多次进行Touch ID验证失败，Touch ID被锁，需要用户输入密码解锁，先Touch ID验证密码
                        {

                            BOOL can = [myContext canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error];
                            if (can) {
                                [myContext evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:@"连续多次指纹或者脸部识别错误，导致touchID或FaceID被锁定" reply:^(BOOL success, NSError * _Nullable error) {
                                    if (!error) {
                                         NSLog(@"密码输入成功！");
                                        [self saveSafeLoginWay:type];
                                    } else {
                                        NSLog(@"密码输入错误！");
                                    }
                                }];
                            }else{
                                NSLog(@"调起账号密码页面失败!!!");
                                
                            }
                            NSLog(@"Touch ID被锁，需要用户输入密码解锁"); // -8 连续五次指纹识别错误，TouchID功能被锁定，下一次需要输入系统密码
                        }
                            break;
                        case LAErrorAppCancel: // Authentication was canceled by application (e.g. invalidate was called while authentication was in progress) 如突然来了电话，电话应用进入前台，APP被挂起啦");
                        {
                            NSLog(@"用户不能控制情况下APP被挂起"); // -9
                        }
                            break;
                        case LAErrorInvalidContext: // LAContext passed to this call has been previously invalidated.
                        {
                            NSLog(@"LAContext传递给这个调用之前已经失效"); // -10
                        }
                            break;
                        default:
                        {
                            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                                NSLog(@"其他情况，切换主线程处理");
                            }];
                            break;
                        }
                    }
                }
            }];
        } else {
            NSLog(@"设备不支持指纹");
            NSLog(@"%ld", (long)authError.code);
            switch (authError.code)
            {
                case LAErrorTouchIDNotEnrolled:
                {
                    NSLog(@"Authentication could not start, because Touch ID has no enrolled fingers");
                    break;
                }
                case LAErrorPasscodeNotSet:
                {
                    NSLog(@"Authentication could not start, because passcode is not set on the device");
                    break;
                }
                default:
                {
                    NSLog(@"TouchID not available");
                    break;
                }
            }
        }
}

- (void)saveSafeLoginWay:(NSString *)type {
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_adapter.type = type;
        if ([type isEqualToString:XLUnlockSettingAdapterFingerprintUnlock]) {
             [XLUserDefaults saveLastLoginWay:XLLoginWayTypeFingerprintUnlock];
        } else if ([type isEqualToString:XLUnlockSettingAdapterBrushFaceUnlock]) {
            [XLUserDefaults saveLastLoginWay:XLLoginWayTypeBrushFaceUnlock];
        }
        [self->_tableView reloadData];
    });
}

#pragma mark - Setter/getter
- (XLTableView *)tableView {
    if (!_tableView) {
        _tableView = [[XLTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor whiteBgColor];
        _tableView.delegate = self.adapter;
        _tableView.dataSource = self.adapter;
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

- (XLUnlockSettingAdapter *)adapter {
    if (!_adapter) {
        _adapter = [[XLUnlockSettingAdapter alloc] init];
        _adapter.adapterDelegate = self;
    }
    return _adapter;
}

@end
